﻿using System.ComponentModel;
using System.Runtime.CompilerServices;
using FixtureManageSystem.Commands;
using FixtureManageSystem.Models;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System;
using System.Linq;
using Borrow = FixtureManageSystem.Models.Borrow;
using Employee = FixtureManageSystem.Models.Employee;
using System.Text.RegularExpressions;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;


namespace FixtureManageSystem.ViewModels
{
    public class BorrowReturnViewMode : ObservableObject
    {

        private ICommand addCommand;
        public ICommand AddCommand
        {
            get { return addCommand; }
            set { addCommand = value; }
        }

        private ICommand getEmployeeCommand;
        public ICommand SearchCommand
        {
            get { return getEmployeeCommand; }
            set { getEmployeeCommand = value; }
        }

        private ICommand updateCommand;
        public ICommand UpdateCommand
        {
            get { return updateCommand; }
            set { updateCommand = value; }
        }
        private ICommand deleteCommand;
        public ICommand DeleteCommand
        {
            get { return deleteCommand; }
            set { deleteCommand = value; }
        }

        private ICommand refreshCommand;
        public ICommand RefreshCommand
        {
            get { return refreshCommand; }
            set { refreshCommand = value; }
        }

        // 显示第一页
        public ICommand BtnFirstCommand { get; set; }
        // 显示前一页
        public ICommand BtnPrevCommand { get; set; }
        // 显示后一页
        public ICommand BtnNextCommand { get; set; }
        // 显示最后一页
        public ICommand BtnLastCommand { get; set; }

        public BorrowService BorrowServiceInst { get; set; }

        private Borrow _borrowReturn;
        public Borrow BorrowReturn
        {
            get { return _borrowReturn; }
            set { _borrowReturn = value; OnPropertyChanged(); }
        }

        private SearchBorrow _searchBorrow;
        public SearchBorrow SearchBorrowInst
        {
            get { return _searchBorrow; }
            set { _searchBorrow = value; OnPropertyChanged(); }
        }

        private ObservableCollection<Borrow> _borrowReturnList;
        public ObservableCollection<Borrow> BorrowReturnList
        {
            get
            {
                return _borrowReturnList;
            }
            set
            {
                _borrowReturnList = value;
                OnPropertyChanged();
            }
        }



        // 是否是搜索模式，搜索模式下，所有数据源放在一个SearchList里面，前端界面仅仅显示SearchList的内容
        // 否则显示数据总条数、页数
        private bool isSearchMode = false;
        // 页码数
        private int page;
        public int Page
        {
            get { return page; }
            set
            {
                page = value;
                OnPropertyChanged();
            }
        }

        // 每页大小
        private int pageSize = 10;
        public int PageSize
        {
            get { return pageSize; }
            set
            {
                if (value != pageSize)
                {
                    pageSize = value;
                    Page = 1;
                    InitBorrowReturnList();
                    OnPropertyChanged();
                }
            }
        }

        // 每页大小的候选项
        private readonly ObservableCollection<int> pageSizes = new ObservableCollection<int>(new int[] { 10, 20, 30, 50, 100 });
        public ObservableCollection<int> PageSizes { get { return pageSizes; } }


        // 总页数
        private int totalCount;
        public int TotalCount { get { return totalCount; } set { totalCount = value; OnPropertyChanged(); } }



        // 搜索结果集，这个集合不能直接显示到前端界面，为了分页方便，所以就存储在这里
        private ObservableCollection<Borrow> searchList = new ObservableCollection<Borrow>();
        public ObservableCollection<Borrow> SearchList
        {
            get
            {
                return searchList;
            }
            set
            {
                searchList = value;
                OnPropertyChanged();
            }
        }

        // 工号的搜索结果集合
        private ObservableCollection<Employee> _searchedEmployees;
        public ObservableCollection<Employee> SearchedEmployees
        {
            get { return _searchedEmployees; }
            set { _searchedEmployees = value; OnPropertyChanged(); }
        }

        // 输入的人名或者工号绑定的searchText
        private string _searchText;
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (value != _searchText)
                {
                    _searchText = value;
                    OnPropertyChanged();
                    Search();
                }

            }
        }

        // combobox下拉列表是否下拉
        private bool _isComboBoxOpen;
        public bool IsComboBoxOpen
        {
            get { return _isComboBoxOpen; }
            set
            {
                _isComboBoxOpen = value;
                OnPropertyChanged();
            }
        }

        // combobox的选中项
        private Employee _selectedPerson;
        public Employee SelectedPerson
        {
            get { return _selectedPerson; }
            set
            {
                if (_selectedPerson != value && value != null)
                {
                    _selectedPerson = value;
                    OnPropertyChanged();
                    SetProperty(ref _searchText, value.SearchName);
                }
            }
        }

        // datagrid的选中项
        private Borrow _selectedBorrow;
        public Borrow SelectedBorrow
        {
            get { return _selectedBorrow; }
            set
            {
                if (value != _selectedBorrow)
                {
                    _selectedBorrow = value;
                    OnPropertyChanged();
                }
            }
        }

        private void Search()
        {
            EmployeeService es = new EmployeeService();
            SearchedEmployees = new ObservableCollection<Employee>(es.GetEmployee(new Employee() { Name = SearchText, PersonNo = SearchText }));
        }

        public BorrowReturnViewMode()
        {
            Page = 1;
            BorrowServiceInst = new BorrowService();
            BorrowReturn = new Borrow();
            SearchBorrowInst = new SearchBorrow();
            AddCommand = new DelegateCommand(Add);
            DeleteCommand = new DelegateCommand(Delete);
            SearchCommand = new DelegateCommand(GetEmployee);
            UpdateCommand = new DelegateCommand(Update);
            RefreshCommand = new DelegateCommand(Refresh);
            BtnFirstCommand = new DelegateCommand(BtnFitst);
            BtnNextCommand = new DelegateCommand(BtnNext);
            BtnLastCommand = new DelegateCommand(BtnLast);
            BtnPrevCommand = new DelegateCommand(BtnPrev);
            InitBorrowReturnList();
        }

        // 初始化显示的参数
        public void InitBorrowReturnList()
        {
            if (!isSearchMode)
            {
                int totalNum = BorrowServiceInst.GetBorrowCount();
                // 计算总页数
                TotalCount = (int)Math.Ceiling((double)totalNum / PageSize);
            }
            else
            {
                TotalCount = (int)Math.Ceiling((double)(SearchList.Count) / PageSize);
            }
            BtnFitst();
        }
        /// <summary>
        /// 跳转到搜索结果或者默认试图的第一页
        /// </summary>

        public void BtnFitst()
        {
            try
            {
                Page = 1;
                // 如果是搜索模式
                if (isSearchMode)
                {
                    BorrowReturnList = new ObservableCollection<Borrow>(SearchList.Skip((Page - 1) * PageSize).Take(PageSize));
                }
                else
                {
                    BorrowReturnList = BorrowServiceInst.InquireBorrow(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }


        /// <summary>
        /// 跳转到搜索结果或者默认试图的前一页
        /// </summary>
        public void BtnPrev()
        {
            if (Page == 1) return;
            Page -= 1;
            try
            {
                // 如果是搜索模式
                if (isSearchMode)
                {

                    BorrowReturnList = new ObservableCollection<Borrow>(SearchList.Skip((Page - 1) * PageSize).Take(PageSize));
                }
                else
                {
                    BorrowReturnList = BorrowServiceInst.InquireBorrow(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        /// <summary>
        /// 跳转到搜索结果或者默认试图的前一页
        /// </summary>
        public void BtnNext()
        {
            if (Page == TotalCount) return;
            Page += 1;
            try
            {
                // 如果是搜索模式
                if (isSearchMode)
                {

                    BorrowReturnList = new ObservableCollection<Borrow>(SearchList.Skip((Page - 1) * PageSize).Take(PageSize));
                }
                else
                {
                    BorrowReturnList = BorrowServiceInst.InquireBorrow(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }


        /// <summary>
        /// 跳转到搜索结果或者默认试图的最后一页
        /// </summary>
        public void BtnLast()
        {
            try
            {
                Page = TotalCount;
                // 如果是搜索模式
                if (isSearchMode)
                {
                    BorrowReturnList = new ObservableCollection<Borrow>(SearchList.Skip((Page - 1) * PageSize).Take(PageSize));
                }
                else
                {
                    BorrowReturnList = BorrowServiceInst.InquireBorrow(Page, PageSize);
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }


        public void Refresh()
        {
            try
            {
                SearchList.Clear();
                isSearchMode = false;
                InitBorrowReturnList();
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        /// <summary>
        /// 消息提示
        /// </summary>
        private string message;
        public string Message
        {
            get { return message; }
            set
            {
                message = value;
                System.Windows.MessageBox.Show(message);
            }
        }

        public void Add()
        {
            try
            {

                if (!BorrowServiceInst.IsExists(BorrowReturn.BarCode))
                {
                    Message = $"未发现物料编码为{BorrowReturn.BarCode}的测试辅料，请先入库该物料！";
                    return;
                }


                if (SelectedPerson is null|| SelectedPerson.SearchName != SearchText)
                {
                    MessageBoxResult result = MessageBox.Show($"领用人{SearchText}不存在于员工库中，是否仍要添加？", "提示", MessageBoxButton.OKCancel);
                    EmployeeService es = new EmployeeService();
                    SelectedPerson = new Employee() { PersonNo = SearchText, Name = SearchText };
                    es.Add(SelectedPerson);

                }

                BorrowReturn.PersonName = SelectedPerson.Name;
                BorrowReturn.PersonNo = SelectedPerson.PersonNo;

                bool isAdded = BorrowServiceInst.Add(BorrowReturn);
                Message = isAdded ? "添加成功" : "添加失败";
                if (isAdded)
                {
                    Refresh();
                }
            }

            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        //搜索
        public void GetEmployee()
        {
            try
            {
                isSearchMode = true;
                SearchList = new ObservableCollection<Borrow>(BorrowServiceInst.Search(SearchBorrowInst));
                InitBorrowReturnList();
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        public void Update()
        {
            if (SelectedBorrow == null)
                return;
            try
            {
                Borrow oldBorrow = BorrowServiceInst.GetBorrowReturn(SelectedBorrow.Id);
                if (oldBorrow == SelectedBorrow)
                    return;
                bool isDeleted = BorrowServiceInst.Update(SelectedBorrow);
                if (isDeleted)
                {
                    Message = "修改成功";
                }
                else
                {
                    Message = "修改失败";
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }

        public void Delete()
        {
            if (SelectedBorrow == null)
                return;
            try
            {
                bool isDeleted = BorrowServiceInst.Delete(SelectedBorrow);
                if (isDeleted)
                {
                    Message = "删除成功";
                    BorrowReturnList.Remove(SelectedBorrow);
                }
                else
                {
                    Message = "删除失败";
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }
    }

}
